package com.second.app.superthread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author GYZ
 * @Date 2024/1/23
 * <pre>
 *  多赛段比赛
 * </pre>
 */
public class CyclicBarrierMoreMatch {

    public static void main(String[] args) {
        CyclicBarrier  cbRef = new CyclicBarrier(2);
        MoreMatchService moreMatchService = new MoreMatchService(cbRef);

        Thread001Run threadRun_ = new Thread001Run(moreMatchService);
        threadRun_.setName("A");
        threadRun_.start();

        Thread001Run threadARun__ = new Thread001Run(moreMatchService);
        threadARun__.setName("B");
        threadARun__.start();

        Thread001Run threadARun__1 = new Thread001Run(moreMatchService);
        threadARun__1.setName("C");
        threadARun__1.start();

        Thread001Run threadARun__2 = new Thread001Run(moreMatchService);
        threadARun__2.setName("D");
        threadARun__2.start();

    }
}

class MoreMatchService {
    private final CyclicBarrier cbRef;

    public MoreMatchService(CyclicBarrier cbRef) {
        this.cbRef = cbRef;
    }

    public void beginRun() {
        try {
            long sleepValue = (int) (Math.random() * 10000);
            Thread.sleep(sleepValue);
            System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + "  begin 跑第1阶段 " +(cbRef.getNumberWaiting()+1));
            cbRef.await();
            System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + "  end 跑第1阶段 " +(cbRef.getNumberWaiting()));

            sleepValue = (int) (Math.random() * 10000);
            Thread.sleep(sleepValue);
            System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + "  begin 跑第2阶段 " +(cbRef.getNumberWaiting()+1));
            cbRef.await();
            System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + "  end 跑第2阶段 " +(cbRef.getNumberWaiting()));
        } catch (InterruptedException | BrokenBarrierException e) {
           e.printStackTrace();
        }

    }
}

class Thread001Run extends Thread{
  private final MoreMatchService  moreMatchService;

  public Thread001Run(MoreMatchService  moreMatchService){
      this.moreMatchService =moreMatchService;
  }

    @Override
    public void run() {
        moreMatchService.beginRun();
    }
}
